package com.aaa.dem1102.d01;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @Author: whj
 * @Version 1.0
 * @Date: 2022/11/2  9:42
 */
public class TestExecutors {
    public static void main(String[] args) {

        //创建单一线程池---池子中有且仅有一个线程对象。
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 5; i++) {
            final  int a = i;
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName()+"***"+a);
                }
            });
        }
        //创建固定长度的线程池----池子中线程的数量是固定的。---里面预先会创建n个线程对象
        ExecutorService executorService1 = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 5; i++) {
            final  int a = i;
            executorService1.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName()+"***"+a);
                }
            });
        }
        //创建可变长度的线程池----根据任务个数动态创建线程对象。
        ExecutorService executorService2 = Executors.newCachedThreadPool();
        for (int i = 0; i < 20; i++) {
            final  int a = i;
            executorService2.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName()+"***"+a);
                }
            });
        }
        //创建延迟线程池:   适合延期执行任务的线程
        ScheduledExecutorService executorService3 = Executors.newScheduledThreadPool(5);
        //往线程池中提交任务。
        for(int i=0;i<5;i++){
            final int a=i;
            executorService3.schedule(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName()+"~~~~~~~~"+a);
                }
            },2, TimeUnit.SECONDS);
        }
    }
}
